import SwiftUI

struct ProfessionalEditView: View {
    let image: UIImage
    @StateObject private var filterEngine = FilterEngine()
    @State private var selectedFilter: FilterEngine.FilterType = .original
    @State private var intensity: Float = 1.0
    @State private var filteredImage: UIImage?
    @State private var filterThumbnails: [FilterEngine.FilterType: UIImage] = [:]
    @State private var isProcessing = false
    @State private var showingShare = false
    @State private var showingIntensitySlider = false
    @Environment(\.dismiss) private var dismiss
    
    var body: some View {
        NavigationStack {
            ZStack {
                Color.black.ignoresSafeArea()
                
                VStack(spacing: 0) {
                    // Top toolbar
                    topToolbar
                    
                    // Main image view
                    imagePreviewSection
                    
                    // Bottom controls
                    bottomControlsSection
                }
            }
        }
        .navigationBarHidden(true)
        .onAppear {
            generateThumbnails()
            applySelectedFilter()
        }
        .sheet(isPresented: $showingShare) {
            ShareSheet(image: filteredImage ?? image)
        }
    }
    
    // MARK: - Top Toolbar
    private var topToolbar: some View {
        HStack {
            // Cancel button
            Button("Cancel") {
                dismiss()
            }
            .font(StyleConstants.Typography.body)
            .foregroundColor(.white)
            
            Spacer()
            
            // Title
            Text(selectedFilter.displayName)
                .font(StyleConstants.Typography.bodyEmphasized)
                .foregroundColor(.white)
            
            Spacer()
            
            // Done button
            Button("Done") {
                saveImage()
            }
            .font(StyleConstants.Typography.bodyEmphasized)
            .foregroundColor(.white)
            .disabled(isProcessing)
        }
        .padding(.horizontal, StyleConstants.Spacing.lg)
        .padding(.vertical, StyleConstants.Spacing.md)
    }
    
    // MARK: - Image Preview Section
    private var imagePreviewSection: some View {
        GeometryReader { geometry in
            ScrollView([.horizontal, .vertical], showsIndicators: false) {
                ZStack {
                    if let displayImage = filteredImage {
                        Image(uiImage: displayImage)
                            .resizable()
                            .aspectRatio(contentMode: .fit)
                            .frame(maxWidth: geometry.size.width, maxHeight: geometry.size.height)
                    } else {
                        Image(uiImage: image)
                            .resizable()
                            .aspectRatio(contentMode: .fit)
                            .frame(maxWidth: geometry.size.width, maxHeight: geometry.size.height)
                    }
                    
                    // Loading indicator
                    if isProcessing {
                        ZStack {
                            Color.black.opacity(0.3)
                            
                            VStack(spacing: StyleConstants.Spacing.sm) {
                                ProgressView()
                                    .progressViewStyle(CircularProgressViewStyle(tint: .white))
                                    .scaleEffect(1.2)
                                
                                Text("Processing...")
                                    .font(StyleConstants.Typography.caption)
                                    .foregroundColor(.white)
                            }
                            .padding(StyleConstants.Spacing.lg)
                            .background(Color.black.opacity(0.6))
                            .cornerRadius(StyleConstants.Layout.cornerRadius)
                        }
                        .cornerRadius(StyleConstants.Layout.cornerRadius)
                    }
                }
            }
        }
        .background(Color.black)
        .clipped()
        // Double tap to compare with original
        .onTapGesture(count: 2) {
            // TODO: Show original image temporarily
        }
        // Long press gesture for intensity adjustment
        .onLongPressGesture {
            withAnimation(StyleConstants.Animation.smooth) {
                showingIntensitySlider.toggle()
            }
        }
    }
    
    // MARK: - Bottom Controls Section
    private var bottomControlsSection: some View {
        VStack(spacing: StyleConstants.Spacing.md) {
            // Intensity slider (conditional)
            if showingIntensitySlider {
                intensitySliderSection
                    .transition(.asymmetric(
                        insertion: .move(edge: .bottom).combined(with: .opacity),
                        removal: .move(edge: .bottom).combined(with: .opacity)
                    ))
            }
            
            // Filter selection
            filterSelectionSection
            
            // Action buttons
            actionButtonsSection
        }
        .padding(.vertical, StyleConstants.Spacing.md)
        .background(
            LinearGradient(
                gradient: Gradient(colors: [
                    Color.clear,
                    Color.black.opacity(0.8),
                    Color.black
                ]),
                startPoint: .top,
                endPoint: .bottom
            )
        )
    }
    
    // MARK: - Intensity Slider Section
    private var intensitySliderSection: some View {
        VStack(spacing: StyleConstants.Spacing.sm) {
            HStack {
                Text("Intensity")
                    .font(StyleConstants.Typography.caption)
                    .foregroundColor(.white.opacity(0.8))
                
                Spacer()
                
                Text("\(Int(intensity * 100))%")
                    .font(StyleConstants.Typography.caption)
                    .foregroundColor(.white)
                    .fontWeight(.medium)
            }
            
            Slider(value: $intensity, in: 0...1, step: 0.1) {
                // Empty label
            } minimumValueLabel: {
                Image(systemName: "sun.min")
                    .font(.system(size: 12))
                    .foregroundColor(.white.opacity(0.6))
            } maximumValueLabel: {
                Image(systemName: "sun.max")
                    .font(.system(size: 12))
                    .foregroundColor(.white.opacity(0.6))
            }
            .accentColor(.white)
            .onChange(of: intensity) { _, _ in
                applySelectedFilter()
            }
        }
        .padding(.horizontal, StyleConstants.Spacing.lg)
        .padding(.vertical, StyleConstants.Spacing.md)
        .background(Color.black.opacity(0.4))
        .cornerRadius(StyleConstants.Layout.cornerRadius)
        .padding(.horizontal, StyleConstants.Spacing.lg)
    }
    
    // MARK: - Filter Selection Section
    private var filterSelectionSection: some View {
        ScrollView(.horizontal, showsIndicators: false) {
            HStack(spacing: StyleConstants.Spacing.md) {
                ForEach(FilterEngine.FilterType.allCases, id: \.self) { filterType in
                    ProfessionalFilterThumbnail(
                        filterType: filterType,
                        thumbnail: filterThumbnails[filterType],
                        isSelected: selectedFilter == filterType
                    ) {
                        withAnimation(StyleConstants.Animation.quick) {
                            selectedFilter = filterType
                        }
                        applySelectedFilter()
                    }
                }
            }
            .padding(.horizontal, StyleConstants.Spacing.lg)
        }
        .frame(height: 100)
    }
    
    // MARK: - Action Buttons Section
    private var actionButtonsSection: some View {
        HStack(spacing: StyleConstants.Spacing.lg) {
            // Intensity adjustment toggle
            Button(action: {
                withAnimation(StyleConstants.Animation.smooth) {
                    showingIntensitySlider.toggle()
                }
            }) {
                VStack(spacing: StyleConstants.Spacing.xs) {
                    Image(systemName: showingIntensitySlider ? "slider.horizontal.below.rectangle" : "slider.horizontal.3")
                        .font(.system(size: 16, weight: .medium))
                        .foregroundColor(showingIntensitySlider ? .white : .white.opacity(0.7))
                    
                    Text("Adjust")
                        .font(StyleConstants.Typography.caption2)
                        .foregroundColor(showingIntensitySlider ? .white : .white.opacity(0.7))
                }
                .frame(width: 60, height: 44)
            }
            
            Spacer()
            
            // Compare with original
            Button(action: {
                // TODO: Toggle between filtered and original
            }) {
                VStack(spacing: StyleConstants.Spacing.xs) {
                    Image(systemName: "rectangle.split.2x1")
                        .font(.system(size: 16, weight: .medium))
                        .foregroundColor(.white.opacity(0.7))
                    
                    Text("Compare")
                        .font(StyleConstants.Typography.caption2)
                        .foregroundColor(.white.opacity(0.7))
                }
                .frame(width: 60, height: 44)
            }
            
            Spacer()
            
            // Share button
            Button(action: {
                showingShare = true
            }) {
                VStack(spacing: StyleConstants.Spacing.xs) {
                    Image(systemName: "square.and.arrow.up")
                        .font(.system(size: 16, weight: .medium))
                        .foregroundColor(.white.opacity(0.7))
                    
                    Text("Share")
                        .font(StyleConstants.Typography.caption2)
                        .foregroundColor(.white.opacity(0.7))
                }
                .frame(width: 60, height: 44)
            }
        }
        .padding(.horizontal, StyleConstants.Spacing.xl)
        .padding(.bottom, StyleConstants.Spacing.md)
    }
    
    // MARK: - Helper Functions
    private func generateThumbnails() {
        DispatchQueue.global(qos: .userInitiated).async {
            for filterType in FilterEngine.FilterType.allCases {
                if let thumbnail = filterEngine.generateThumbnail(from: image, filterType: filterType) {
                    DispatchQueue.main.async {
                        filterThumbnails[filterType] = thumbnail
                    }
                }
            }
        }
    }
    
    private func applySelectedFilter() {
        isProcessing = true
        
        DispatchQueue.global(qos: .userInitiated).async {
            let result = filterEngine.applyFilter(
                to: image,
                filterType: selectedFilter,
                intensity: intensity
            )
            
            DispatchQueue.main.async {
                filteredImage = result
                isProcessing = false
            }
        }
    }
    
    private func saveImage() {
        guard let imageToSave = filteredImage ?? image else { return }
        
        UIImageWriteToSavedPhotosAlbum(imageToSave, nil, nil, nil)
        
        // Show success feedback
        let impactFeedback = UIImpactFeedbackGenerator(style: .light)
        impactFeedback.impactOccurred()
        
        dismiss()
    }
}

// MARK: - Professional Filter Thumbnail
struct ProfessionalFilterThumbnail: View {
    let filterType: FilterEngine.FilterType
    let thumbnail: UIImage?
    let isSelected: Bool
    let onTap: () -> Void
    
    var body: some View {
        VStack(spacing: StyleConstants.Spacing.xs) {
            ZStack {
                // Background
                RoundedRectangle(cornerRadius: StyleConstants.Layout.smallCornerRadius)
                    .fill(Color.gray.opacity(0.3))
                    .frame(width: 64, height: 64)
                
                if let thumbnail = thumbnail {
                    Image(uiImage: thumbnail)
                        .resizable()
                        .aspectRatio(contentMode: .fill)
                        .frame(width: 64, height: 64)
                        .clipped()
                        .cornerRadius(StyleConstants.Layout.smallCornerRadius)
                } else {
                    ProgressView()
                        .progressViewStyle(CircularProgressViewStyle(tint: .white))
                        .scaleEffect(0.8)
                        .frame(width: 64, height: 64)
                }
            }
            .overlay(
                RoundedRectangle(cornerRadius: StyleConstants.Layout.smallCornerRadius)
                    .stroke(
                        isSelected ? Color.white : Color.white.opacity(0.3),
                        lineWidth: isSelected ? 2 : 1
                    )
            )
            .scaleEffect(isSelected ? 1.05 : 1.0)
            .shadow(
                color: isSelected ? .white.opacity(0.3) : .clear,
                radius: isSelected ? 4 : 0,
                x: 0,
                y: 0
            )
            .animation(StyleConstants.Animation.quick, value: isSelected)
            
            Text(filterType.displayName)
                .font(StyleConstants.Typography.caption2)
                .foregroundColor(isSelected ? .white : .white.opacity(0.7))
                .fontWeight(isSelected ? .medium : .regular)
                .lineLimit(1)
                .frame(width: 64)
        }
        .onTapGesture {
            onTap()
        }
    }
}

// MARK: - Share Sheet
struct ShareSheet: UIViewControllerRepresentable {
    let image: UIImage
    
    func makeUIViewController(context: Context) -> UIActivityViewController {
        let activityController = UIActivityViewController(
            activityItems: [image],
            applicationActivities: nil
        )
        return activityController
    }
    
    func updateUIViewController(_ uiViewController: UIActivityViewController, context: Context) {}
}

#Preview {
    if let sampleImage = UIImage(systemName: "photo") {
        ProfessionalEditView(image: sampleImage)
            .preferredColorScheme(.dark)
    }
}